﻿<template>
  <div>
    <el-dialog v-drag :title = 'dialogTitle' :visible.sync = 'dialogFormVisible' width='40%' @close = "closeDialog"
    :close-on-click-modal = 'false'>
      <el-form :model = "ruleForm" ref = "ruleForm" :label-width = 'labelWidth' :rules = 'rules'>
        <el-form-item label = "来源表名称：">
           <el-input v-model = "ruleForm.fromTableName" disabled></el-input>
        </el-form-item>
        <el-form-item label = "目标表名称：" prop = 'toTableName'>
          <el-input v-model = 'ruleForm.toTableName' placeholder = "请输入目标表名称"></el-input>
        </el-form-item>
        <el-form-item label = "是否复制数据：">
          <el-switch v-model = 'ruleForm.isCopyData'></el-switch>
        </el-form-item>
        <el-form-item class = 'form_noLeftMargin'>
          <el-button  type = 'info' @click = "resetForm ('ruleForm')">取 消</el-button>
          <el-button type = "primary" @click = "submitForm ('ruleForm')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ['copyTableDialog', 'currentTable'],
  data () {
    return {
      dialogTitle: '复制一个元数据表并创建目标表',
      dialogFormVisible: false,
      labelWidth: '110px',
      ruleForm: {
        fromTableName: '',
        toTableName: '',
        isCopyData: false
      },
      rules: {
        toTableName: [
          {required: true, message: '目标表名称不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    // 点击取消按钮时
    resetForm (forms) {
      this.$refs[forms].resetFields()
      this.$emit('giveUpCopyTable')
    },
    // 点击上部的X关闭弹窗时
    closeDialog () {
      this.$refs.ruleForm.resetFields()
      this.$emit('giveUpCopyTable')
    },
    // 点击确定提交的按钮时
    submitForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.$post('/metadata/' + this.currentTable.metauid + '/copytable', {
            to_table: this.ruleForm.toTableName,
            with_data: this.ruleForm.isCopyData
          }).then(data => {
            if (data.data.result.code === 'failed') {
              this.$message({
                message: data.data.result.msg,
                type: 'warning'
              })
            } else if (data.data.result.code === 'success') {
              this.$message({
                message: '元数据表复制成功',
                type: 'success'
              })
              this.$refs[forms].resetFields()
              this.$emit('sureCopyTable')
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false
        }
      })
    }
  },
  watch: {
    copyTableDialog: {
      handler: function (val, oldVal) {
        this.dialogFormVisible = val
        if (val) {
          this.ruleForm.fromTableName = this.currentTable.metaname
          this.ruleForm.toTableName = ''
          this.ruleForm.isCopyData = false
        }
      },
      deep: true
    }
  }
}
</script>
